package com.snackshop.controller;

import cn.hutool.jwt.JWTUtil;
import com.snackshop.config.JwtConfiguration;
import com.snackshop.pojo.vo.LoginVO;
import com.snackshop.pojo.vo.R;
import com.snackshop.pojo.vo.ResponseState;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 登陆
 *
 * @author Kinfer
 * @date 2022/11/16
 */
@Log
@RestController
public class LoginController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtConfiguration jwtConfiguration;

    @PostMapping("/login")
    public R login(LoginVO loginVO) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginVO.getUserPhone(), loginVO.getUserPassword());
        authenticationManager.authenticate(authenticationToken);
        // 执行到这，说明登陆成功
        Map<String, Object> map = Map.of("userPhone", loginVO.getUserPhone());
        // 创建token
        String token = JWTUtil.createToken(map, jwtConfiguration.getKey().getBytes());
        // 返回给客户端
        Map<String, Object> tokenMap = Map.of("token", token);
        return R.RESULT(ResponseState.SUCCESS, tokenMap);
    }
}
